package com.example.weight.greenSeasons.SolidLiquid;
import com.example.weight.R;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.config.Config;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class shebeiyunxing7_1 extends AppCompatActivity {

    private TitleBar titleBar;
    //日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");//HH:mm
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm:ss");
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView worm_incoming_incomeDate;
    //备注
    private EditText remark;
    //用户、抄表人
    private String name, role, factory;

    private RadioGroup yijing_group;

    private TextView jilu;

    private TextView shiftStatus;

    private String currentShift, equipment_name = null;

    private String jiluText = "";

    private Button mBtnOn1, mBtnOff1, mBtnSave;

    private Map<String, Boolean> btnStatus = new HashMap<String, Boolean>();

    private StringBuilder record = new StringBuilder("");

    @SuppressLint("HandlerLeak")
    private Handler recordHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 0){
                getRecord();
            }
        }
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shebeiyunxing7_1);

        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        yijing_group = findViewById(R.id.yijing_group);
        jilu = findViewById(R.id.jilu);
        jilu.setMovementMethod(ScrollingMovementMethod.getInstance());
        jilu.setSelected(true);
        jilu.setFocusable(false);
        shiftStatus = findViewById(R.id.shiftStatus);
        mBtnOn1 = findViewById(R.id.button1);
        mBtnOff1 = findViewById(R.id.button2);
        mBtnSave = findViewById(R.id.btn_save);

        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });

        //日期
        worm_incoming_incomeDate = findViewById(R.id.worm_incoming_incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));
        //备注
        remark = findViewById(R.id.worm_incoming_remark);

        //用户和职责
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        yijing_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                equipment_name = radioButton.getText().toString();
                if(btnStatus.get(equipment_name) != null && !btnStatus.get(equipment_name)){
                    setOprBtnDisable();
                }else {
                    setOprBtnEnable();
                }
            }
        });

        try {
            if(Utility.belongCalendar(df.parse(df.format(new Date())), df.parse("00:00"), df.parse("12:00"))){
                currentShift = "白班";
            }else {
                currentShift = "晚班";
            }
            shiftStatus.setText("班次: "+currentShift);
            Log.d("shiftSet", currentShift);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        this.getRecord();
    }

    public void startUp(View view) throws ParseException {
        if(equipment_name == null){
            Toast.makeText(shebeiyunxing7_1.this, "请选择设备", Toast.LENGTH_SHORT).show();
        } else
            new AlertDialog.Builder(shebeiyunxing7_1.this)
                    .setTitle("确定开机吗？")
                    .setCancelable(false)
                    .setNegativeButton("取消", ((dialog, which) -> {
                    }))
                    .setPositiveButton("确定", (dialog, which) -> {
                        String url = null;
                        RequestQueue queue = Volley.newRequestQueue(this);
                        url = Config.url + "/sjq/solidliquidProduceEquipmentRunning/addOnTime";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code = jsonObject.getString("code");

                                            if (code.startsWith("2"))
                                                Toast.makeText(shebeiyunxing7_1.this,
                                                        "提交成功", Toast.LENGTH_SHORT).show();
                                            else
                                                Toast.makeText(shebeiyunxing7_1.this,
                                                        "提交失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(shebeiyunxing7_1.this,
                                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                @SuppressLint("SimpleDateFormat")
                                Map<String, String> map = new HashMap<>();
                                map.put("equipment_name", equipment_name);
                                map.put("operator", name);
                                map.put("factory", factory);
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                        recordHandler.sendEmptyMessageDelayed(0, 500);
                    })
                    .show();
    }

    public void shutDown(View view) throws ParseException {
        if(equipment_name == null){
            Toast.makeText(shebeiyunxing7_1.this, "请选择设备", Toast.LENGTH_SHORT).show();
        } else
            new AlertDialog.Builder(this)
                    .setTitle("确定保存吗？")
                    .setCancelable(false)
                    .setNegativeButton("取消", ((dialog, which) -> {
                    }))
                    .setPositiveButton("确定", (dialog, which) -> {

                        Date time1 = new Date();

                        RequestQueue queue = Volley.newRequestQueue(this);
                        String url = Config.url + "/sjq/solidliquidProduceEquipmentRunning/addOffTime";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Log.d("zys", response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            Log.d("zys", jsonObject.getString("code"));
                                            Date time2 = new Date();
                                            //long inter = time2.getTime() - time1.getTime();

                                            if (jsonObject.getString("code").startsWith("2"))
                                                Toast.makeText(shebeiyunxing7_1.this,
                                                        "提交成功", Toast.LENGTH_SHORT).show();
                                            else
                                                Toast.makeText(shebeiyunxing7_1.this,
                                                        "失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(shebeiyunxing7_1.this,
                                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                @SuppressLint("SimpleDateFormat")
                                Map<String, String> map = new HashMap<>();
                                map.put("equipment_name", equipment_name);
                                map.put("operator", name);
                                map.put("factory", factory);
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                        recordHandler.sendEmptyMessageDelayed(0, 500);
                    })
                    .show();
    }

    //提交按钮
    public void save(View view) {
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/solidliquidProduceEquipmentRunning/addRemarks";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Toast.makeText(shebeiyunxing7_1.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(shebeiyunxing7_1.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(shebeiyunxing7_1.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(shebeiyunxing7_1.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", equipment_name);
                            map.put("remarks", remark.getText().toString());
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                    recordHandler.sendEmptyMessageDelayed(0, 500);
                })
                .show();

    }


    private void setOprBtnDisable(){
        mBtnOn1.setEnabled(false);
        mBtnOff1.setEnabled(false);
    }

    private void setOprBtnEnable() {
        mBtnOn1.setEnabled(true);
        mBtnOff1.setEnabled(true);
    }

    private void getRecord(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/solidliquidProduceEquipmentRunning/getListOnTheDay" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray datas = jsonObject.getJSONArray("data");
                            JSONObject data;
                            if(jilu.getText() != null){
                                record.delete(0, record.length());
                            }
                            if (!jsonObject.isNull("data")) {
                                for(int i=0;i<datas.length();i++){
                                    data = datas.getJSONObject(i);
                                    if(!data.getString("onTime1").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("onTime1")).append("开机\n");
                                    }
                                    if(!data.getString("offTime1").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("offTime1")).append("关机\n");
                                    }
                                    if(!data.getString("onTime2").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("onTime2")).append("开机\n");
                                    }
                                    if(!data.getString("offTime2").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("offTime2")).append("关机\n");
                                    }
                                    jilu.setText(record.toString());
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(shebeiyunxing7_1.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

}